package com.zhangsun.newMvvm.base.model;

import com.zhangsun.newMvvm.common.network.exception.ExceptionEngine;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class BaseRepository<T> {

    /**
     * 管理RxJava请求
     */
    private CompositeDisposable compositeDisposable;

    public void setObserver(Observable<T> observable, Observer<T> observer) {
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .onErrorResumeNext((Function<Throwable, ObservableSource<T>>) throwable -> Observable.error(ExceptionEngine.handleException(throwable)))
                .subscribe(observer);
    }

    /**
     * 添加 rxJava 发出的请求
     *
     * @param disposable 请求
     */
    protected void addDisposable(Disposable disposable) {
        if (compositeDisposable == null || compositeDisposable.isDisposed()) {
            compositeDisposable = new CompositeDisposable();
        }
        compositeDisposable.add(disposable);
    }

    protected void dispose() {
        if (compositeDisposable != null) {
            compositeDisposable.dispose();
            compositeDisposable = null;
        }
    }

}
